# PPH System File Copy Script (PowerShell)
# This script handles Chinese paths and encoding issues better than batch files

Write-Host "PPH Production File Copy Script" -ForegroundColor Green
Write-Host "=================================" -ForegroundColor Green
Write-Host ""

# Set paths - Get the actual current directory to avoid encoding issues
$CurrentDir = Get-Location
$DeployDir = Split-Path -Parent $PSScriptRoot
$AppDir = Join-Path $DeployDir "app"

# Try to find the source directory automatically
$PossibleSources = @(
    "D:\OneDrive\Desktop\新PPH项目",
    (Join-Path (Split-Path $DeployDir -Parent) ""),
    "D:\新PPH项目",
    "C:\新PPH项目"
)

$SourceDir = $null
foreach ($path in $PossibleSources) {
    if (Test-Path $path -and (Test-Path (Join-Path $path "backend")) -and (Test-Path (Join-Path $path "frontend"))) {
        $SourceDir = $path
        break
    }
}

# If not found automatically, use the parent directory of deployment package
if (-not $SourceDir) {
    $ParentDir = Split-Path $DeployDir -Parent
    if (Test-Path (Join-Path $ParentDir "backend") -and Test-Path (Join-Path $ParentDir "frontend")) {
        $SourceDir = $ParentDir
    }
}

Write-Host "Source Directory: $SourceDir" -ForegroundColor Yellow
Write-Host "Deploy Directory: $DeployDir" -ForegroundColor Yellow
Write-Host "App Directory: $AppDir" -ForegroundColor Yellow
Write-Host ""

# Check if source exists
if (-not $SourceDir -or -not (Test-Path $SourceDir)) {
    Write-Host "ERROR: Source directory not found!" -ForegroundColor Red
    Write-Host ""
    Write-Host "Searched in the following locations:" -ForegroundColor Yellow
    foreach ($path in $PossibleSources) {
        $exists = Test-Path $path
        Write-Host "  $path - $(if($exists){'EXISTS'}else{'NOT FOUND'})" -ForegroundColor $(if($exists){'Green'}else{'Red'})
    }
    Write-Host ""
    Write-Host "Please ensure your PPH project is in one of these locations," -ForegroundColor Yellow
    Write-Host "or manually set the correct path in this script." -ForegroundColor Yellow
    Write-Host ""
    Write-Host "Manual solution:" -ForegroundColor Cyan
    Write-Host "1. Edit Copy-Files.ps1" -ForegroundColor White
    Write-Host "2. Find line with: `$PossibleSources = @(" -ForegroundColor White
    Write-Host "3. Add your actual path to the list" -ForegroundColor White
    Read-Host "Press Enter to exit"
    exit 1
}

# Create target directories
Write-Host "Creating target directories..." -ForegroundColor Cyan
$null = New-Item -ItemType Directory -Path $AppDir -Force
$null = New-Item -ItemType Directory -Path "$AppDir\backend" -Force
$null = New-Item -ItemType Directory -Path "$AppDir\frontend" -Force
$null = New-Item -ItemType Directory -Path "$AppDir\backend\data" -Force
$null = New-Item -ItemType Directory -Path "$AppDir\logs" -Force
Write-Host "✓ Directories created" -ForegroundColor Green
Write-Host ""

# Copy backend files
Write-Host "Copying backend files..." -ForegroundColor Cyan
$BackendSource = Join-Path $SourceDir "backend"
$BackendTarget = Join-Path $AppDir "backend"

if (Test-Path $BackendSource) {
    # Copy all backend files except excluded folders
    $ExcludeDirs = @("node_modules", ".git", "logs", "uploads", "temp", "dist")
    
    Get-ChildItem -Path $BackendSource -Recurse | Where-Object {
        $relativePath = $_.FullName.Substring($BackendSource.Length)
        $shouldExclude = $false
        foreach ($excludeDir in $ExcludeDirs) {
            if ($relativePath -like "*\$excludeDir\*" -or $relativePath -like "*\$excludeDir") {
                $shouldExclude = $true
                break
            }
        }
        -not $shouldExclude -and $_.Name -notlike "*.log" -and $_.Name -notlike "*.tmp" -and $_.Name -ne "package-lock.json"
    } | ForEach-Object {
        $targetPath = $_.FullName.Replace($BackendSource, $BackendTarget)
        $targetDir = Split-Path $targetPath -Parent
        
        if (-not (Test-Path $targetDir)) {
            $null = New-Item -ItemType Directory -Path $targetDir -Force
        }
        
        if (-not $_.PSIsContainer) {
            Copy-Item $_.FullName $targetPath -Force
        }
    }
    Write-Host "✓ Backend files copied" -ForegroundColor Green
} else {
    Write-Host "⚠ Backend folder not found" -ForegroundColor Yellow
}
Write-Host ""

# Copy frontend files
Write-Host "Copying frontend files..." -ForegroundColor Cyan
$FrontendSource = Join-Path $SourceDir "frontend"
$FrontendTarget = Join-Path $AppDir "frontend"

if (Test-Path $FrontendSource) {
    # Copy all frontend files except excluded folders
    $ExcludeDirs = @("node_modules", ".git", "dist", "logs")
    
    Get-ChildItem -Path $FrontendSource -Recurse | Where-Object {
        $relativePath = $_.FullName.Substring($FrontendSource.Length)
        $shouldExclude = $false
        foreach ($excludeDir in $ExcludeDirs) {
            if ($relativePath -like "*\$excludeDir\*" -or $relativePath -like "*\$excludeDir") {
                $shouldExclude = $true
                break
            }
        }
        -not $shouldExclude -and $_.Name -notlike "*.log" -and $_.Name -notlike "*.tmp" -and $_.Name -ne "package-lock.json"
    } | ForEach-Object {
        $targetPath = $_.FullName.Replace($FrontendSource, $FrontendTarget)
        $targetDir = Split-Path $targetPath -Parent
        
        if (-not (Test-Path $targetDir)) {
            $null = New-Item -ItemType Directory -Path $targetDir -Force
        }
        
        if (-not $_.PSIsContainer) {
            Copy-Item $_.FullName $targetPath -Force
        }
    }
    Write-Host "✓ Frontend files copied" -ForegroundColor Green
} else {
    Write-Host "⚠ Frontend folder not found" -ForegroundColor Yellow
}
Write-Host ""

# Copy database file
Write-Host "Copying database file..." -ForegroundColor Cyan
$DatabaseSource = Join-Path $SourceDir "backend\data\pph.sqlite"
$DatabaseTarget = Join-Path $AppDir "backend\data\pph.sqlite"

if (Test-Path $DatabaseSource) {
    Copy-Item $DatabaseSource $DatabaseTarget -Force
    Write-Host "✓ Database file copied" -ForegroundColor Green
} else {
    Write-Host "⚠ Database file not found" -ForegroundColor Yellow
}
Write-Host ""

# Copy other important files
Write-Host "Copying other important files..." -ForegroundColor Cyan

$OtherFiles = @(
    "check-staff-fields.cjs",
    "legacyDb.db",
    "package.json"
)

foreach ($file in $OtherFiles) {
    $sourceFile = Join-Path $SourceDir $file
    $targetFile = Join-Path $AppDir $file
    
    if (Test-Path $sourceFile) {
        Copy-Item $sourceFile $targetFile -Force
        Write-Host "✓ $file copied" -ForegroundColor Green
    } else {
        Write-Host "⚠ $file not found" -ForegroundColor Yellow
    }
}
Write-Host ""

# Verify key files
Write-Host "Verifying copied files..." -ForegroundColor Cyan
$KeyFiles = @(
    "backend\server-simple.cjs",
    "backend\package.json",
    "frontend\package.json",
    "frontend\index.html",
    "backend\data\pph.sqlite"
)

$allFilesPresent = $true
foreach ($file in $KeyFiles) {
    $filePath = Join-Path $AppDir $file
    if (Test-Path $filePath) {
        Write-Host "✓ $file exists" -ForegroundColor Green
    } else {
        Write-Host "✗ $file missing" -ForegroundColor Red
        $allFilesPresent = $false
    }
}

Write-Host ""
if ($allFilesPresent) {
    Write-Host "🎉 All key files copied successfully!" -ForegroundColor Green
} else {
    Write-Host "⚠ Some key files are missing. Please check manually." -ForegroundColor Yellow
}

Write-Host ""
Write-Host "=================================" -ForegroundColor Green
Write-Host "File copy completed!" -ForegroundColor Green
Write-Host "=================================" -ForegroundColor Green
Write-Host ""
Write-Host "Next steps:" -ForegroundColor Yellow
Write-Host "1. Run: scripts\install-dependencies.bat" -ForegroundColor White
Write-Host "2. Run: scripts\deploy-cmd.bat" -ForegroundColor White
Write-Host ""

Read-Host "Press Enter to continue"
